package com.joyd.autobot

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.BroadcastReceiver
import android.content.pm.PackageManager
import android.content.SharedPreferences
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.activity.result.contract.ActivityResultContracts
import com.joyd.joydlib.io.WebSocketClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okio.ByteString
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger

class MainActivity : AppCompatActivity(), WebSocketForegroundService.Companion.ServiceReadyCallback {
    private val TAG = "MainActivity"
    private val SCREENSHOT_COMMAND = "screenshot"
    private val REQUEST_NOTIFICATION_PERMISSION = 1002
    // 定义截图数据广播的action
    private val SCREENSHOT_DATA_ACTION = "com.joyd.autobot.SCREENSHOT_DATA"
    private val SCREENSHOT_DATA_EXTRA = "screenshot_data"
    // 定义MediaProjection权限请求广播的action
    private val MEDIA_PROJECTION_PERMISSION_REQUIRED = "com.joyd.autobot.MEDIA_PROJECTION_PERMISSION_REQUIRED"
    
    private lateinit var connectButton: Button
    private lateinit var connectionStatusIndicator: View
    private lateinit var connectionStatusText: TextView
    private lateinit var settingsButton: Button
    private lateinit var webSocketUrl: String
    private var webSocketClient: WebSocketClient? = null
    private var isConnected = false
    
    // WebSocket健康检查相关常量
    private val HEALTH_CHECK_INTERVAL_MS = 10000L // 健康检查间隔10秒
    private val PING_INTERVAL_MS = 30000L // Ping发送间隔30秒
    private val PONG_TIMEOUT_MS = 45000L // Pong超时时间45秒
    private val RECONNECT_DELAY_MS = 5000L // 重连延迟5秒
    
    // 用于跟踪ping/pong时间
    private var lastPingTime = System.currentTimeMillis()
    private var lastPongTime = System.currentTimeMillis()
    
    // 健康检查相关的Handler和Runnable
    private var healthCheckHandler: Handler? = null
    private var healthCheckRunnable: Runnable? = null
    
    // 重连状态标志
    private val isReconnecting = AtomicBoolean(false)
    
    // 处理异步事件的Handler
    private lateinit var handler: Handler
    
    // UI组件引用
    private var screenshotButton: Button? = null
    
    // 创建截图数据广播接收器
    private val screenshotBroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == SCREENSHOT_DATA_ACTION) {
                val screenshotData = intent.getByteArrayExtra(SCREENSHOT_DATA_EXTRA)
                if (screenshotData != null) {
                    Log.d(TAG, "接收到截图数据，大小: ${screenshotData.size} bytes")
                    // 发送截图数据到服务端
                    sendScreenshotData(screenshotData)
                } else {
                    Log.e(TAG, "接收到的截图数据为null")
                }
            } else if (intent?.action == MEDIA_PROJECTION_PERMISSION_REQUIRED) {
                // 接收到需要重新请求MediaProjection权限的广播
                Log.d(TAG, "接收到需要重新请求MediaProjection权限的广播")
                runOnUiThread {
                    Toast.makeText(this@MainActivity, "需要重新请求屏幕捕获权限以继续截图功能", Toast.LENGTH_SHORT).show()
                    requestScreenshotPermission()
                }
            }
        }
    }
    // Activity Result API launcher for media projection
    private val mediaProjectionLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK && result.data != null) {
            Log.d(TAG, "用户授予了屏幕捕获权限")
            WebSocketForegroundService.setMediaProjection(this, result.resultCode, result.data!!)
        } else {
            // 用户拒绝了屏幕捕获权限
            Log.d(TAG, "用户拒绝了屏幕捕获权限，resultCode: ${result.resultCode}")
            Toast.makeText(this, "需要屏幕捕获权限才能执行截图操作", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        Log.d(TAG, "onCreate()被调用")
        
        // 初始化Handler
        handler = Handler(Looper.getMainLooper())
        
        // 初始化UI组件
        initUI()
        
        // 从SharedPreferences获取配置的WebSocket URL
        val sharedPreferences = androidx.preference.PreferenceManager.getDefaultSharedPreferences(this)
        val defaultUrl = getString(R.string.web_socket_url)
        webSocketUrl = sharedPreferences.getString(getString(R.string.pref_key_web_socket_url), defaultUrl) ?: defaultUrl
        Log.d(TAG, "从配置获取WebSocket URL: $webSocketUrl")
        
        // 初始化WebSocket客户端
        initWebSocketClient()
        
        // 检查并请求通知权限
        checkNotificationPermission()
        
        // 注册截图数据广播接收器
        registerScreenshotBroadcastReceiver()
    }
    
    // 注册截图数据广播接收器
    private fun registerScreenshotBroadcastReceiver() {
        val filter = IntentFilter()
        filter.addAction(SCREENSHOT_DATA_ACTION)
        filter.addAction(MEDIA_PROJECTION_PERMISSION_REQUIRED)
        ContextCompat.registerReceiver(
            this,
            screenshotBroadcastReceiver,
            filter,
            ContextCompat.RECEIVER_NOT_EXPORTED
        )
        Log.d(TAG, "截图数据广播接收器和MediaProjection权限请求广播接收器已注册")
    }
    
    // 注销截图数据广播接收器
    private fun unregisterScreenshotBroadcastReceiver() {
        try {
            unregisterReceiver(screenshotBroadcastReceiver)
            Log.d(TAG, "截图数据广播接收器已注销")
        } catch (e: Exception) {
            Log.e(TAG, "注销广播接收器异常: ${e.message}", e)
        }
    }
    private fun initUI() {
        connectButton = findViewById<Button>(R.id.connect_button)
        connectionStatusIndicator = findViewById<View>(R.id.connection_status_indicator)
        connectionStatusText = findViewById<TextView>(R.id.connection_status_text)
        settingsButton = findViewById<Button>(R.id.settings_btn)
        
        // 初始状态设置为未连接
        updateConnectionStatus(false)
        
        // 设置连接按钮点击事件
        setupConnectButton()
        
        // 设置设置按钮点击事件
        setupSettingsButton()
    }

    private fun checkNotificationPermission() {
        // Android 13及以上需要通知权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "通知权限未授予，请求权限")
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_NOTIFICATION_PERMISSION)
            } else {
                Log.d(TAG, "通知权限已授予")
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            REQUEST_NOTIFICATION_PERMISSION -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "用户授予了通知权限")
                } else {
                    Log.w(TAG, "用户拒绝了通知权限")
                    Toast.makeText(this, "需要通知权限以在后台保持WebSocket连接", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun initWebSocketClient() {
        try {
            Log.d(TAG, "开始初始化WebSocket客户端")
            
            // 创建WebSocket客户端实例
            webSocketClient = WebSocketClient(webSocketUrl)
            if (webSocketClient == null) {
                Log.e(TAG, "WebSocketClient创建失败，对象为null")
                return
            }
            
            Log.d(TAG, "WebSocket客户端创建成功: $webSocketClient")
            
            // 配置重连参数
            val reconnectConfigResult = webSocketClient?.setReconnectConfig(
                maxAttempts = 10,           // 最大重连次数
                baseDelayMs = 1000L,        // 基础重连延迟（毫秒）
                maxDelayMs = 30000L         // 最大重连延迟（毫秒）
            )
            
            Log.d(TAG, "WebSocket重连参数配置完成，结果: $reconnectConfigResult")
            
            // 设置消息接收回调
            val messageCallbackResult = webSocketClient?.setOnMessageCallback {
                // 处理接收到的文本消息
            Log.d(TAG, "收到WebSocket消息: $it")
            
            // 检查是否是截屏命令
            if (it == SCREENSHOT_COMMAND) {
                Log.d(TAG, "收到截屏命令，开始执行截屏操作")
                // 在后台线程执行截屏操作
                Thread {
                    try {
                        takeScreenshot()
                    } catch (e: Exception) {
                        Log.e(TAG, "执行截屏操作异常: ${e.message}", e)
                    }
                }.start()
                } else {
                    runOnUiThread {
                        Toast.makeText(this@MainActivity, "收到消息: $it", Toast.LENGTH_SHORT).show()
                        // 收到消息意味着连接成功，如果UI还显示未连接，强制更新UI
                        if (!isConnected) {
                            Log.d(TAG, "收到消息但isConnected为false，强制更新UI为连接状态")
                            isConnected = true
                            updateConnectionStatus(true)
                        }
                    }
                }
            }
            
            Log.d(TAG, "WebSocket消息接收回调设置完成，结果: $messageCallbackResult")
            
            // 设置连接状态变化回调 - 简化实现，主要依赖Flow
            val stateCallbackResult = webSocketClient?.setOnStateChangeCallback { state ->
                // 处理连接状态变化
                Log.d(TAG, "WebSocket连接状态变化: $state")
                
                // 状态变化日志
                val statusMessage = when(state) {
                    WebSocketClient.ConnectionState.Disconnected -> "连接已断开"
                    WebSocketClient.ConnectionState.Connecting -> "正在连接"
                    WebSocketClient.ConnectionState.Connected -> "WebSocket连接成功"
                    WebSocketClient.ConnectionState.Paused -> "连接已暂停"
                    else -> "未知状态"
                }
                Log.d(TAG, "显示Toast消息: $statusMessage")
                runOnUiThread {
                    Toast.makeText(this@MainActivity, statusMessage, Toast.LENGTH_SHORT).show()
                }
            }
            
            Log.d(TAG, "WebSocket连接状态回调设置完成，结果: $stateCallbackResult")
            
            // 设置错误回调
            val errorCallbackResult = webSocketClient?.setOnErrorCallback {
                Log.e(TAG, "WebSocket连接错误: ${it?.message}")
                runOnUiThread {
                    val errorMsg = it?.message ?: "未知错误"
                    Toast.makeText(this@MainActivity, "WebSocket连接错误: $errorMsg", Toast.LENGTH_SHORT).show()
                }
            }
            
            Log.d(TAG, "WebSocket错误回调设置完成")
            Log.d(TAG, "WebSocket客户端初始化完成")
        } catch (e: Exception) {
            Log.e(TAG, "初始化WebSocket失败: ${e.message}", e)
            runOnUiThread {
                Toast.makeText(this, "初始化WebSocket失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 执行截屏操作
     * 现在通过前台服务请求截图
     */
    private fun takeScreenshot() {
        Log.d(TAG, "takeScreenshot方法被调用")
        
        // 检查WebSocket连接状态
        if (!isConnected) {
            Log.w(TAG, "WebSocket未连接，无法发送截图")
            runOnUiThread {
                Toast.makeText(this, "WebSocket未连接，请先连接", Toast.LENGTH_SHORT).show()
            }
            return
        }
        
        // 获取当前服务实例状态
        val service = WebSocketForegroundService.getInstance()
        Log.d(TAG, "当前服务实例状态: $service")
        
        // 确保前台服务已启动
        if (service == null) {
            Log.d(TAG, "前台服务未启动，先启动服务")
            WebSocketForegroundService.startService(this)
            Log.d(TAG, "前台服务启动命令已发送")
            
            // 增加尝试次数计数器
            val attempts = AtomicInteger(0)
            val maxAttempts = 5
            
            // 延迟尝试截图，给服务启动时间
            val handler = Handler(Looper.getMainLooper())
            val runnable = object : Runnable {
                override fun run() {
                    val currentAttempt = attempts.incrementAndGet()
                    
                    if (currentAttempt <= maxAttempts) {
                        val currentService = WebSocketForegroundService.getInstance()
                        Log.d(TAG, "尝试 #$currentAttempt 检查服务状态: $currentService")
                        
                        if (currentService == null) {
                            Log.d(TAG, "服务仍未启动，$currentAttempt 秒后再次尝试")
                            handler.postDelayed(this, 1000)
                        } else {
                            Log.d(TAG, "服务已成功启动，开始截图操作")
                            takeScreenshot()
                        }
                    } else {
                        Log.e(TAG, "服务启动超时，无法完成截图操作")
                        runOnUiThread {
                            Toast.makeText(this@MainActivity, "服务启动超时，截图失败", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
            
            handler.postDelayed(runnable, 1000)
            return
        }
        
        Log.d(TAG, "服务实例已获取，正在检查MediaProjection状态")
        
        // 直接通过前台服务请求截图
        try {
            // 先检查是否已有可用的MediaProjection实例
            if (WebSocketForegroundService.hasActiveMediaProjection()) {
                Log.d(TAG, "发现已有可用的MediaProjection实例，直接请求截图")
                val currentService = WebSocketForegroundService.getInstance()
                Log.d(TAG, "获取到的前台服务实例: $currentService")
                if (currentService != null) {
                        Log.d(TAG, "调用服务的requestScreenshotSafely方法")
                        currentService.requestScreenshotSafely()
                    } else {
                        Log.e(TAG, "前台服务实例获取失败，无法请求截图")
                        runOnUiThread {
                            Toast.makeText(this@MainActivity, "截图服务不可用", Toast.LENGTH_SHORT).show()
                        }
                    }
                return
            } else {
                Log.d(TAG, "没有可用的MediaProjection实例")
            }
            
            // 如果没有可用的MediaProjection实例，启动服务并请求权限
            Log.d(TAG, "准备启动服务并请求MediaProjection权限")
            WebSocketForegroundService.startServiceForMediaProjection(this, object : WebSocketForegroundService.Companion.ServiceReadyCallback {
                override fun onServiceReady() {
                    Log.d(TAG, "服务已准备就绪，开始请求权限")
                    // 服务启动后，请求权限
                    runOnUiThread {
                        val mainActivity = this@MainActivity
                        try {
                            val mediaProjectionManager = mainActivity.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
                            val captureIntent = mediaProjectionManager.createScreenCaptureIntent()
                            Log.d(TAG, "创建了屏幕捕获意图，准备启动权限请求对话框")
                            mainActivity.mediaProjectionLauncher.launch(captureIntent)
                            Log.d(TAG, "权限请求对话框已启动")
                        } catch (e: Exception) {
                            Log.e(TAG, "创建屏幕捕获意图失败: ${e.message}", e)
                            Toast.makeText(mainActivity, "无法请求截图权限: ${e.message}", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })
        } catch (e: Exception) {
            Log.e(TAG, "启动截图服务失败: ${e.message}", e)
            runOnUiThread {
                Toast.makeText(this@MainActivity, "截图失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    override fun onServiceReady() {
        Log.d(TAG, "前台服务已准备就绪，请求屏幕捕获权限")
        requestScreenshotPermission()
    }
    
    // 请求截图权限的方法
    private fun requestScreenshotPermission() {
        try {
            // 检查是否有MediaProjection权限
            val mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
            val captureIntent = mediaProjectionManager.createScreenCaptureIntent()
            mediaProjectionLauncher.launch(captureIntent)
        } catch (e: Exception) {
            Log.e(TAG, "请求截图权限失败", e)
            runOnUiThread {
                Toast.makeText(this, "请求截图权限失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 发送截图数据到服务端
     */
    fun sendScreenshotData(data: ByteArray) {
        try {
            // 检查WebSocket客户端是否连接
            if (webSocketClient != null && isConnected) {
                // 直接发送二进制数据
                val byteString = ByteString.of(*data)
                val sendResult = webSocketClient?.send(byteString)
                Log.d(TAG, "发送二进制截图数据结果: $sendResult")
                Log.d(TAG, "发送的二进制数据大小: ${data.size} 字节")
            } else {
                Log.e(TAG, "WebSocket未连接，无法发送截图数据")
            }
        } catch (e: Exception) {
            Log.e(TAG, "发送截图数据异常: ${e.message}", e)
        }
    }

    private fun setupConnectButton() {
        connectButton.setOnClickListener { 
            if (isConnected) {
                // 断开连接
                disconnect()
            } else {
                // 建立连接
                connect()
                
                // 添加连接超时检查
                val mainHandler = Handler(Looper.getMainLooper())
                mainHandler.postDelayed({ 
                    if (!isConnected) {
                        Log.w(TAG, "连接超时检查: 5秒后仍未连接成功，当前状态: $isConnected")
                        // 由于服务端显示连接成功但客户端未收到回调，尝试强制检查一次
                        Log.d(TAG, "连接超时检查: 尝试获取WebSocket客户端的实际连接状态")
                        
                        // 主动检查连接状态并更新UI
                        val actualConnectedState = checkWebSocketConnectionState()
                        Log.d(TAG, "连接超时检查: 主动检查的连接状态: $actualConnectedState")
                        
                        if (actualConnectedState) {
                            isConnected = true
                            updateConnectionStatus(true)
                        }
                    }
                }, 5000)
            }
        }
    }

    /**
     * 设置设置按钮的点击事件
     */
    private fun setupSettingsButton() {
        settingsButton.setOnClickListener {
            // 启动设置页面
            val intent = Intent(this, SettingsActivity::class.java)
            startActivity(intent)
        }
    }
    
    /**
     * 尝试主动检查WebSocket的连接状态
     * 这是一个辅助方法，用于在状态回调可能未被触发的情况下检查连接状态
     */
    // 检查WebSocket连接状态
    private fun checkWebSocketConnectionState(): Boolean {
        try {
            // 先检查客户端实例是否存在
            if (webSocketClient == null) {
                Log.d(TAG, "WebSocket client is null")
                return false
            }
            
            // 获取当前连接状态
            val actualConnectedState = webSocketClient!!.connectionState.value == WebSocketClient.ConnectionState.Connected
            Log.d(TAG, "WebSocket connection state: $actualConnectedState")
            
            // 如果连接状态为true，额外发送ping测试以确保连接是活跃的
            if (actualConnectedState) {
                try {
                    // 发送ping消息来验证连接状态
                    val message = "ping:${System.currentTimeMillis()}"
                    webSocketClient!!.send(message)
                    Log.d(TAG, "Sent ping message to verify connection")
                    
                    // 设置最近一次ping时间
                    lastPingTime = System.currentTimeMillis()
                } catch (e: Exception) {
                    Log.w(TAG, "Failed to send ping message", e)
                    // ping发送失败，可能连接已经断开
                    return false
                }
            }
            
            // 更新类变量isConnected
            this.isConnected = actualConnectedState
            
            // 更新UI显示的连接状态
            runOnUiThread {
                updateConnectionStatus(actualConnectedState)
            }
            
            return actualConnectedState
        } catch (e: Exception) {
            Log.e(TAG, "Error checking WebSocket connection state", e)
            runOnUiThread {
                updateConnectionStatus(false)
            }
            return false
        }
    }

    /**
     * 连接到WebSocket服务器
     */
    fun connect(): Boolean {
        // 检查webSocketClient实例是否存在
        if (webSocketClient == null) {
            Log.e(TAG, "WebSocket client is not initialized")
            return false
        }
        
        try {
            // 检查当前连接状态，如果已经连接则先断开
            if (webSocketClient!!.connectionState.value == WebSocketClient.ConnectionState.Connected) {
                Log.d(TAG, "WebSocket is already connected, disconnecting first")
                webSocketClient!!.disconnect()
            }
            
            // 连接到WebSocket服务器
            webSocketClient!!.connect()
            Log.d(TAG, "Attempting to connect to WebSocket server")
            
            // 等待连接建立，最多等待5秒
            val startTime = System.currentTimeMillis()
            val timeout = 5000 // 5秒超时
            while (webSocketClient!!.connectionState.value != WebSocketClient.ConnectionState.Connected && System.currentTimeMillis() - startTime < timeout) {
                Thread.sleep(100)
            }
            
            val isConnected = webSocketClient!!.connectionState.value == WebSocketClient.ConnectionState.Connected
            Log.d(TAG, "WebSocket connection result: $isConnected")
            
            // 检查连接是否成功
            if (isConnected) {
                // 启动定时检查连接状态的任务
                startConnectionHealthCheck()
                
                // 更新UI显示的连接状态
                runOnUiThread {
                    updateConnectionStatus(true)
                }
            } else {
                // 连接失败，记录日志
                Log.e(TAG, "Failed to connect to WebSocket server within timeout")
            }
            
            // 更新类变量isConnected
            this.isConnected = isConnected
            return isConnected
        } catch (e: Exception) {
            Log.e(TAG, "Error connecting to WebSocket server", e)
            return false
        }
    }

    /**
     * 断开WebSocket连接
     */
    fun disconnect() {
        // 取消连接健康检查任务
        stopConnectionHealthCheck()
        
        try {
            if (webSocketClient != null && webSocketClient!!.connectionState.value == WebSocketClient.ConnectionState.Connected) {
                webSocketClient!!.disconnect()
                Log.d(TAG, "WebSocket disconnected")
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error disconnecting WebSocket", e)
        }
    }

    /**
     * 启动连接健康检查任务
     */
    private fun startConnectionHealthCheck() {
        // 先取消已有的检查任务
        stopConnectionHealthCheck()
        
        // 创建新的健康检查任务
        healthCheckHandler = Handler(Looper.getMainLooper())
        healthCheckRunnable = object : Runnable {
            override fun run() {
                try {
                    // 检查连接状态
                    val isConnected = webSocketClient?.connectionState?.value == WebSocketClient.ConnectionState.Connected
                    
                    // 检查最后一次ping时间是否超过阈值
                    val currentTime = System.currentTimeMillis()
                    val timeSinceLastPing = currentTime - lastPingTime
                    val timeSinceLastPong = currentTime - lastPongTime
                    
                    // 如果长时间没有收到pong响应，认为连接已断开
                    if (isConnected && timeSinceLastPong > PONG_TIMEOUT_MS) {
                        Log.w(TAG, "WebSocket connection timeout, no pong response")
                        // 尝试重新连接
                        handler.post {
                            reconnectWebSocket()
                        }
                    } else if (isConnected && timeSinceLastPing > PING_INTERVAL_MS) {
                        // 发送ping消息
                        try {
                            val message = "ping:${currentTime}"
                            webSocketClient?.send(message)
                            lastPingTime = currentTime
                            Log.d(TAG, "Health check: sent ping message")
                        } catch (e: Exception) {
                            Log.w(TAG, "Failed to send ping during health check", e)
                        }
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "Error in connection health check", e)
                } finally {
                    // 继续调度下一次检查
                    healthCheckHandler?.postDelayed(this, HEALTH_CHECK_INTERVAL_MS)
                }
            }
        }
        
        // 开始执行健康检查任务
        healthCheckHandler?.postDelayed(healthCheckRunnable!!, HEALTH_CHECK_INTERVAL_MS)
        Log.d(TAG, "Connection health check started")
    }

    /**
     * 停止连接健康检查任务
     */
    private fun stopConnectionHealthCheck() {
        try {
            if (healthCheckHandler != null && healthCheckRunnable != null) {
                healthCheckHandler!!.removeCallbacks(healthCheckRunnable!!)
                healthCheckHandler = null
                healthCheckRunnable = null
                Log.d(TAG, "Connection health check stopped")
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error stopping connection health check", e)
        }
    }

    /**
     * 重新连接WebSocket
     */
    private fun reconnectWebSocket() {
        try {
            // 标记重连中状态
            isReconnecting.set(true)
            
            // 断开现有连接
            disconnect()
            
            // 延迟一段时间后重新连接
            Handler(Looper.getMainLooper()).postDelayed({
                try {
                    Log.d(TAG, "Attempting to reconnect WebSocket")
                    connect()
                } catch (e: Exception) {
                    Log.e(TAG, "Reconnection failed", e)
                } finally {
                    isReconnecting.set(false)
                }
            }, RECONNECT_DELAY_MS)
        } catch (e: Exception) {
            Log.e(TAG, "Error during reconnection", e)
            isReconnecting.set(false)
        }
    }

    // 更新连接状态显示
    private fun updateConnectionStatus(isConnected: Boolean) {
        try {
            if (!isFinishing) {
                runOnUiThread {
                    try {
                        // 更新连接状态文本和图标
                        connectionStatusText.text = if (isConnected) "已连接" else "未连接"
                        connectionStatusText.setTextColor(
                            if (isConnected) android.graphics.Color.GREEN else android.graphics.Color.RED
                        )
                        
                        // 更新连接按钮状态
                        connectButton.isEnabled = (!isConnected) && (!isReconnecting.get())
                        
                        // 更新连接状态指示器
                        connectionStatusIndicator.setBackgroundResource(
                            if (isConnected) R.drawable.connection_status_circle_connected else R.drawable.connection_status_circle
                        )
                    } catch (e: Exception) {
                        Log.e(TAG, "Error updating UI in updateConnectionStatus", e)
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error in updateConnectionStatus", e)
        }
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "onPause()被调用，应用进入后台")
        
        // 如果WebSocket连接已建立，启动前台服务以保持连接
        if (isConnected) {
            Log.d(TAG, "WebSocket已连接，启动前台服务")
            WebSocketForegroundService.startService(this)
        }
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG, "onStop()被调用")
        
        // 双重检查，如果WebSocket连接已建立但前台服务未启动，这里再启动一次
        if (isConnected) {
            Log.d(TAG, "onStop(): WebSocket已连接，确认前台服务状态")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy()被调用，释放资源")
        
        // 停止前台服务
        WebSocketForegroundService.stopService(this)
        
        // 确保在Activity销毁时释放WebSocket资源
        webSocketClient?.release()
        webSocketClient = null
        
        // 注销截图数据广播接收器
        unregisterScreenshotBroadcastReceiver()
    }
}